package 剑指Offer.medium;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class 从上到下打印二叉树3 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> res = new ArrayList<>();
            Deque<TreeNode> queue = new LinkedList<>();
            if (root != null) {
                queue.addLast(root);
            }
            int i = 0;
            while (!queue.isEmpty()) {
                int size = queue.size();
                List<Integer> tmp = new ArrayList<>();
                if (i % 2 == 0) {
                    for (int k = 0; k < size; k++) {
                        TreeNode node = queue.pollFirst();
                        tmp.add(node.val);
                        if (node.left != null) queue.addLast(node.left);
                        if (node.right != null) queue.addLast(node.right);
                    }
                }
                if (i % 2 == 1) {
                    for (int k = 0; k < size; k++) {
                        TreeNode node = queue.pollLast();
                        tmp.add(node.val);
                        if (node.right != null) queue.addFirst(node.right);
                        if (node.left != null) queue.addFirst(node.left);
                    }
                }
                res.add(tmp);
                i++;
            }
            return res;
        }
    }
}
